package com.sm.li.controller;

import com.sm.li.common.http.AxiosResult;

import com.sm.li.common.perm.HasPerm;
import com.sm.li.common.valid.group.AddGroup;
import com.sm.li.common.valid.group.UpdateGroup;
import com.sm.li.components.EmailService;
import com.sm.li.controller.base.BaseController;
import com.sm.li.dto.ScheduleDTO;
import com.sm.li.entity.Admin;
import com.sm.li.entity.ScheduleBean;

import com.sm.li.mapper.AdminMapper;
import com.sm.li.service.ScheduleService;
import com.sm.li.transfer.ScheduleTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@RestController
@RequestMapping("schedule")
public class ScheduleController extends BaseController {
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private ScheduleTransfer scheduleTransfer;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private EmailService emailService;

    private Map<Long, ScheduledFuture> map = new HashMap<>();

    @PostConstruct
    public void initSchedule() {
        List<ScheduleBean> list = scheduleService.list();
        list.forEach(scheduleBean -> {
            String cronExpress = scheduleBean.getCronExpress();
            CronTrigger cronTrigger = new CronTrigger(cronExpress);


            ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(new Runnable() {
                @Override
                public void run() {
                    //给这里面的员工发邮件
                    List<Admin> admins = adminMapper.selectList(null);
                    admins.forEach(admin -> {
                        emailService.sendMail(admin);
                    });
                }
            }, cronTrigger);
            map.put(scheduleBean.getCronId(), scheduledFuture);
        });
    }

    @GetMapping
    public AxiosResult<List<ScheduleDTO>> list() {
        return AxiosResult.success(scheduleTransfer.toDTO(scheduleService.list()));
    }

    @GetMapping("{id}")
    public AxiosResult<ScheduleDTO> findById(@PathVariable Long id) {
        return AxiosResult.success(scheduleTransfer.toDTO(scheduleService.findById(id)));
    }


    @PostMapping
    public AxiosResult add(@RequestBody ScheduleBean scheduleBean) {

        return toAxios(scheduleService.addSchedule(scheduleBean));
    }

    @PutMapping
    @HasPerm(permSign = "tesk:time:updete")
    public AxiosResult<Void> update(@RequestBody ScheduleBean scheduleBean) {
        Long cronId = scheduleBean.getCronId();
        ScheduledFuture scheduledFuture = map.get(cronId);
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(false);
        }
        map.remove(cronId);
        int i = scheduleService.updateSchedule(scheduleBean);
        ScheduledFuture scheduledFuture1 =     threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                //给这里面的员工发邮件
                List<Admin> admins = adminMapper.selectList(null);
                admins.forEach(admin -> {
                    emailService.sendMail(admin);
                });
            }
        }, new CronTrigger(scheduleBean.getCronExpress()));

        map.put(cronId,scheduledFuture1);
        return toAxios(i);
    }

    @DeleteMapping("{id}")
    @HasPerm(permSign = "tesk:time:delete")
    public AxiosResult<Void> deleteById(@PathVariable Long id) {
        int i = scheduleService.deleteById(id);
        ScheduledFuture scheduledFuture = map.get(id);
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(true);
        }
        map.remove(id);
        return toAxios(i);

    }

    @PutMapping("{id}")
    @HasPerm(permSign = "task:time:pause")
    public AxiosResult<Void> pause(@PathVariable Long id) {
        ScheduledFuture scheduledFuture = map.get(id);
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            //停掉
            scheduledFuture.cancel(false);
            //删掉
            map.remove(id);
        }
        return AxiosResult.success();
    }

    @PostMapping("{id}")
    @HasPerm(permSign = "task:time:resume")
    public AxiosResult<Void> resume(@PathVariable Long id) {
        ScheduleBean byId = scheduleService.findById(id);
        ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                //给这里面的员工发邮件
                List<Admin> admins = adminMapper.selectList(null);
                admins.forEach(admin -> {
                    emailService.sendMail(admin);
                });
            }
        }, new CronTrigger(byId.getCronExpress()));
        map.put(byId.getCronId(), scheduledFuture);
        return AxiosResult.success();
    }

}
